"use strict";

const semver = require("semver");
const colors = require("colors/safe");
const log = require("@azir-cli/log");
const LOWEST_NODE_VERSION = "12.0.0";

class Command {
  constructor(argv) {
    if (!argv) {
      throw new Error("argv is required");
    }
    if (!Array.isArray(argv)) {
      throw new Error("argv must be an array");
    }
    if (argv.length < 1) {
      throw new Error("参数长度必须大于1");
    }
    this._argv = argv;
    let runner = new Promise(() => {
      let chain = Promise.resolve();
      chain = chain.then(() => {
        this.checkNodeVersion();
      });
      chain = chain.then(() => {
        this.initArgv();
      });
      chain = chain.then(() => {
        this.init();
      });
      chain = chain.then(async() => {
        this.exec();
      });
      chain.catch((err) => {
        log.error(err.message);
      });
    });
  }

  initArgv() {
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1);
  }

  exec() {
    throw new Error("exec() must be implemented");
  }

  init() {
    throw new Error("init() must be implemented");
  }

  checkNodeVersion() {
    //1. 检查当前 node 版本
    const currentNodeVersion = process.version;
    //2. 对比最低版本号
    if (!semver.gte(currentNodeVersion, LOWEST_NODE_VERSION)) {
      throw new Error(
        colors.red(`azir 需要安装 v${LOWEST_NODE_VERSION} 以上版本的 Node.js`)
      );
    }
  }
}

module.exports = Command;
